package com.qf.logistics.security;

import com.qf.logistics.security.handler.MySuccessHandler;
import com.qf.logistics.security.service.MyUserSetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * created by 赵文韬 on 2022/3/30 15:18
 */
@Component
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true,proxyTargetClass = true)//开启注解进行权限判断
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    private MySuccessHandler mySuccessHandler;

    @Autowired
    private MyUserSetailService myUserSetailService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    public void setMySuccessHandler(MySuccessHandler mySuccessHandler) {
        this.mySuccessHandler = mySuccessHandler;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserSetailService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()//认证请求
                .and().formLogin()//sprringsecurity给我们提供了一个默认的登录页面,默认地址就是/login, 我们可以改
                //  .disable()///禁用默认的登录方式
//                .loginPage("/login.html")//自定义登录页面
//                .loginProcessingUrl("/login")
                .successHandler(mySuccessHandler)
                // .usernameParameter("uName")//自定义用户名的参数,默认是username,如果是用的默认页面,可以忽略,写了也白写
                // .passwordParameter("pwd")//自定义密码的参数名
                .permitAll()//放行.登录地址是不需要拦截,所谓的放行是先到security然后发现不需要拦截,就放行
                .and().logout().
                logoutUrl("/logout").permitAll()//自定义退出的地址,这个地址也不需要你写,security会自动退出并清理登录数据
                .and().authorizeRequests().anyRequest()//任意地址,除了上面单独配置的其他地址
                .authenticated();//必须登录才可以访问,是否需要登录取决于业务
    }
}
